package com.resou.reader.reader.animation;

import android.animation.ValueAnimator;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.animation.DecelerateInterpolator;
import android.widget.Toast;

import com.resou.reader.reader.manager.BookStatus;
import com.resou.reader.reader.utils.ScreenUtils;
import com.resou.reader.reader.view.PageView;
import com.resou.reader.utils.log.DLog;

/**
 * Created by ${Garrett} on 2018/9/28.
 * Contact me krouky@outlook.com
 */
public class CoverAnimation extends BaseAnimation {

    private static final String TAG = "SlideAnimation1";
    //分页位置
    private float currPagePosition = 0.01f;

    private float downX;

    /**
     * 当前页
     */
    private Bitmap mCurrPageBitmap;
    /**
     * 下一页
     */
    private Bitmap mNextPageBitmap;

    private Canvas mCurrPageCanvas;
    private Canvas mNextPageCanvas;

    private PageView view;

    public CoverAnimation() {
        Point size = new Point();
        ScreenUtils.getScreenSize(size);
        int width = (size.x > 0) ? size.x : ScreenUtils.getScreenWidth();
        int height = (size.y > 0) ? size.y : ScreenUtils.getScreenHeight();
        try {
            onDestory();
            mCurrPageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
            mNextPageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
            mCurrPageCanvas = new Canvas(mCurrPageBitmap);
            mNextPageCanvas = new Canvas(mNextPageBitmap);
        } catch (OutOfMemoryError e) {
            Log.i(TAG, "CoverAnimation: " + e.getMessage());
        }


//        pageFactory.onDraw(mCurrPageCanvas);
    }

    @Override
    public void onMeasure(int width, int height) {

    }

    @Override
    public void onDraw(Canvas canvas) {
        drawCurrPage(canvas);
        drawNextPage(canvas);
        drawShade(canvas);
    }

    private void drawCurrPage(Canvas canvas) {
        canvas.save();
        if (currPagePosition < 0) {
            canvas.translate(currPagePosition, 0);
        } else {
            RectF rectF = new RectF(currPagePosition, 0, view.getWidth(), view.getHeight());
            canvas.clipRect(rectF);
        }
        if (mCurrPageBitmap != null && !mCurrPageBitmap.isRecycled()) {
            canvas.drawBitmap(mCurrPageBitmap, 0, 0, null);
        }
        canvas.restore();
    }

    private void drawNextPage(Canvas canvas) {
        canvas.save();
        if (currPagePosition < 0) {
            RectF rectF = new RectF(view.getWidth() + currPagePosition, 0, view.getWidth(), view.getHeight());
            canvas.clipRect(rectF);
        } else {
            canvas.translate(currPagePosition - view.getWidth(), 0);//currPagePosition - view.getWidth()
        }
        if (mNextPageBitmap != null && !mNextPageBitmap.isRecycled()) {
            canvas.drawBitmap(mNextPageBitmap, 0, 0, null);
        }
        canvas.restore();
    }


    private void drawShade(Canvas canvas) {
        if (currPagePosition == 0 || currPagePosition == -view.getWidth()) {
            return;
        }
        canvas.save();
        if (currPagePosition > 0) {
            canvas.translate(currPagePosition, 0);
        } else {
            canvas.translate(view.getWidth() + currPagePosition, 0);
        }
        canvas.drawRect(0, 0, 40, view.getHeight(), mPaint);
        canvas.restore();
    }

    private float dx;
    private int pageState = -1;
    private long downTime = 0;
    private boolean isFirstSlide = true;
    private boolean hasNoNextOrPrePage = false;
    private boolean duringAnimation = false;
    private ValueAnimator va;
    private VelocityTracker mVelocityTracker = VelocityTracker.obtain();
    boolean firstClick = true;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (duringAnimation) {
            va.end();
        }
        float x = event.getX();
        mVelocityTracker.addMovement(event);
//        boolean consume = mGestureDetector.onTouchEvent(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                firstClick = false;
                downX = x;
                long t1 = System.currentTimeMillis();
                if (t1 - downTime < 350) {
                    return false;
                }
                downTime = t1;
                pageFactory.onDraw(mCurrPageCanvas);
                return true;
            case MotionEvent.ACTION_MOVE:
                float moveDx = x - downX;
                if (!isFirstSlide && moveDx * this.dx <= 0) {
                    return true;
                } else {
                    this.dx = moveDx;
                }
//                DLog.d(SlideAnimation.class.getSimpleName(), "dx == " + dx);
                if (isFirstSlide && Math.abs(x - downX) >= 5) {
                    isFirstSlide = false;
                    if (dx < 0) {//向左滑动
                        pageState = pageFactory.nextPage();
                        if (pageState == BookStatus.NO_NEXT_PAGE || pageState == BookStatus.NO_NEXT_CHAPTER) {
//                            Toast.makeText(view.getContext(), "没有下一页啦", Toast.LENGTH_SHORT).show();
                            pageFactory.startEndBookPage();
                            hasNoNextOrPrePage = true;
                        } else if (pageState == BookStatus.LOAD_SUCCESS || pageState == 2) {
                            pageFactory.onDraw(mNextPageCanvas);
                            hasNoNextOrPrePage = false;
                        } else {
                            hasNoNextOrPrePage = true;
                        }
                    } else {//向右滑动
                        pageState = pageFactory.prePage();
                        if (pageState == BookStatus.NO_PRE_PAGE) {
                            Toast.makeText(view.getContext(), "没有上一页啦", Toast.LENGTH_SHORT).show();
                            hasNoNextOrPrePage = true;
                        } else if (pageState == BookStatus.LOAD_SUCCESS || pageState == 2) {
                            pageFactory.onDraw(mNextPageCanvas);
                            hasNoNextOrPrePage = false;
                        } else {
                            hasNoNextOrPrePage = true;
                        }
                    }
                }
                if (hasNoNextOrPrePage) {
                    return true;
                }
                currPagePosition = dx;
                view.postInvalidate();
                break;
            case MotionEvent.ACTION_UP:
            default:
                firstClick = false;
                float upDx = x - downX;
                /**
                 * 广告页显示的时候让其刷新
                 */
                if (pageFactory.isNexPage() && pageFactory.isAdPrePage()) {
                    pageFactory.refreshAd();
                }
                isFirstSlide = true;

                final float animationStart = currPagePosition;
                mVelocityTracker.computeCurrentVelocity(1000);
//                DLog.d(SlideAnimation.class.getSimpleName(), "XVelocity == " + mVelocityTracker.getXVelocity());
                duringAnimation = true;

                if (System.currentTimeMillis() - downTime < 1000 && pageState < 0/*说明还没有处理过翻页逻辑*/) {//单击
                    va = ValueAnimator.ofFloat(0, 0);
                    if (downX < view.getWidth() / 2) {// move to pre page
                        pageState = pageFactory.prePage();
                        if (pageState == BookStatus.NO_PRE_PAGE) {
                            Toast.makeText(view.getContext(), "没有上一页啦", Toast.LENGTH_SHORT).show();
                            hasNoNextOrPrePage = true;
                        } else if (pageState == BookStatus.LOAD_SUCCESS || pageState == 2) {
                            va = ValueAnimator.ofFloat(0, view.getWidth());
                            pageFactory.onDraw(mNextPageCanvas);
                            hasNoNextOrPrePage = false;
                        } else {
                            hasNoNextOrPrePage = true;
                        }
                    } else {//move to next page
                        pageState = pageFactory.nextPage();
                        if (pageState == BookStatus.NO_NEXT_PAGE || pageState == BookStatus.NO_NEXT_CHAPTER) {
//                            Toast.makeText(view.getContext(), "没有下一页啦", Toast.LENGTH_SHORT).show();
                            pageFactory.startEndBookPage();
                            hasNoNextOrPrePage = true;
                        } else if (pageState == BookStatus.LOAD_SUCCESS || pageState == 2) {
                            va = ValueAnimator.ofFloat(0, -view.getWidth());
                            pageFactory.onDraw(mNextPageCanvas);
                            hasNoNextOrPrePage = false;
                        } else {
                            hasNoNextOrPrePage = true;
                        }
                    }
                } else {
                    if (hasNoNextOrPrePage) {//下一页或者上一页没有数据
                        va = ValueAnimator.ofFloat(animationStart, 0);
                        return true;
                    } else if (upDx * this.dx < 0) {// 反向
                        DLog.d(SlideAnimation.class.getSimpleName(), "1111cancel!,isCancelNextPage:" + (currPagePosition < 0));
                        va = ValueAnimator.ofFloat(animationStart, 0);
                        if (pageState >= 0)
                            pageFactory.cancel(currPagePosition < 0);
                    } else if (currPagePosition >= view.getWidth() / 2 || (currPagePosition > 0 && mVelocityTracker.getXVelocity() >= 50)) { // move to pre page
                        va = ValueAnimator.ofFloat(animationStart, view.getWidth());
                    } else if (currPagePosition < -view.getWidth() / 2 || (currPagePosition < 0 && mVelocityTracker.getXVelocity() <= -80)) {//move to next page
                        va = ValueAnimator.ofFloat(animationStart, -view.getWidth());
                    } else {//cancel
                        DLog.d(SlideAnimation.class.getSimpleName(), "cancel!,isCancelNextPage:" + (currPagePosition < 0));
                        va = ValueAnimator.ofFloat(animationStart, 0);
                        if (pageState >= 0)
                            pageFactory.cancel(currPagePosition < 0);
                    }
                }
                va.setInterpolator(new DecelerateInterpolator());
                va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        currPagePosition = (float) animation.getAnimatedValue();
                        view.postInvalidate();
                        if (Math.abs(currPagePosition) == view.getWidth()) {
                            pageFactory.onDraw(mCurrPageCanvas);
                            duringAnimation = false;
                        } else if (currPagePosition == 0) {
                            duringAnimation = false;
                        }
                    }
                });
                va.setDuration(300).start();
                pageState = -1;
                break;
        }
        return false;
    }

    @Override
    public void bindView(PageView pageView) {
        this.view = pageView;
        init();
    }

    private Paint mPaint;

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        LinearGradient linearGradient = new LinearGradient(0, 0, 40, 0, 0x44111111, 0x00111111, LinearGradient.TileMode.MIRROR);
        mPaint.setShader(linearGradient);
    }

    @Override
    public void computeScroll() {

    }

    @Override
    public void onDestory() {
        if (mCurrPageBitmap != null && !mCurrPageBitmap.isRecycled()) {
            mCurrPageCanvas = null;
            mCurrPageBitmap.recycle();
            mCurrPageBitmap = null;
        }
        if (mNextPageBitmap != null && !mNextPageBitmap.isRecycled()) {
            mNextPageCanvas = null;
            mNextPageBitmap.recycle();
            mNextPageBitmap = null;
        }
    }

    @Override
    public void refreshCurrPage() {
        if (firstClick) {
            pageFactory.onDraw(mCurrPageCanvas);
        }
    }

    @Override
    public void refreshNextPage() {
        pageFactory.onDraw(mNextPageCanvas);
    }

    @Override
    public void nextPage() {
        int status = pageFactory.nextPage();
        if (status == BookStatus.NO_NEXT_PAGE) {
            Toast.makeText(view.getContext(), "没有下一页啦", Toast.LENGTH_SHORT).show();
            return;
        } else if (status == BookStatus.LOAD_SUCCESS) {
//            if (isPrepared) {
            pageFactory.onDraw(mCurrPageCanvas);
            pageFactory.onDraw(mNextPageCanvas);
            view.postInvalidate();
//            }
        } else {
            return;
        }
    }

    @Override
    public void prePage() {
        int status = pageFactory.prePage();
        if (status == BookStatus.NO_PRE_PAGE) {
            Toast.makeText(view.getContext(), "", Toast.LENGTH_SHORT).show();
            return;
        } else if (status == BookStatus.LOAD_SUCCESS) {
//            if (isPrepared) {
            pageFactory.onDraw(mCurrPageCanvas);
            pageFactory.onDraw(mNextPageCanvas);
            view.postInvalidate();
//        }
        } else {
            return;
        }
    }
}
